<template>
  <div class="users-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索用户名或邮箱"
        class="search-input"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 用户列表 -->
    <el-table :data="users" v-loading="loading" style="width: 100%">
      <el-table-column prop="ID" label="ID" width="80" />
      <el-table-column prop="Username" label="用户名" />
      <el-table-column prop="Email" label="邮箱" />
      <el-table-column prop="Role" label="角色" width="100">
        <template #default="{ row }">
          <el-tag :type="row.Role === 'admin' ? 'danger' : 'info'">
            {{ row.Role }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="Status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.Status === 'active' ? 'success' : 'danger'">
            {{ row.Status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="Points" label="积分" width="100" />
      <el-table-column prop="LastLoginAt" label="最后登录" width="180">
        <template #default="{ row }">
          {{ row.LastLoginAt ? formatDate(row.LastLoginAt) : '从未登录' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleViewDetails(row)">
            查看详情
          </el-button>
          <el-button
            size="small"
            :type="row.Status === 'active' ? 'danger' : 'success'"
            @click="handleUpdateStatus(row, row.Status === 'active' ? 'blocked' : 'active')"
          >
            {{ row.Status === 'active' ? '封禁' : '解封' }}
          </el-button>
          <el-button size="small" type="primary" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="loadUsers"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="用户详情"
      width="50%"
    >
      <template v-if="currentUser">
        <div class="user-details">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户ID">{{ currentUser.ID }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{ currentUser.Username }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ currentUser.Email }}</el-descriptions-item>
            <el-descriptions-item label="角色">{{ currentUser.Role }}</el-descriptions-item>
            <el-descriptions-item label="状态">{{ currentUser.Status }}</el-descriptions-item>
            <el-descriptions-item label="积分">{{ currentUser.Points }}</el-descriptions-item>
            <el-descriptions-item label="注册时间">
              {{ formatDate(currentUser.CreatedAt) }}
            </el-descriptions-item>
            <el-descriptions-item label="最后登录">
              {{ currentUser.LastLoginAt ? formatDate(currentUser.LastLoginAt) : '从未登录' }}
            </el-descriptions-item>
          </el-descriptions>

          <!-- 用户统计信息 -->
          <h3 style="margin-top: 20px">统计信息</h3>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="总订单数">
              {{ currentUser.stats?.total_orders || 0 }}
            </el-descriptions-item>
            <el-descriptions-item label="总消费">
              ¥{{ currentUser.stats?.total_amount || 0 }}
            </el-descriptions-item>
            <el-descriptions-item label="平均订单金额">
              ¥{{ currentUser.stats?.avg_order_amount || 0 }}
            </el-descriptions-item>
          </el-descriptions>

          <!-- 用户偏好设置 -->
          <h3 style="margin-top: 20px">偏好设置</h3>
          <el-descriptions :column="2" border v-if="currentUser.preference">
            <el-descriptions-item label="喜好分类">
              <el-tag 
                v-for="category in currentUser.preference.fav_categories"
                :key="category"
                style="margin-right: 4px"
              >
                {{ category }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="口味标签">
              <el-tag 
                v-for="tag in currentUser.preference.fav_tags"
                :key="tag"
                style="margin-right: 4px"
              >
                {{ tag }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="辣度偏好">
              <el-rate
                :model-value="currentUser.preference.spicy_level"
                disabled
                :max="3"
              />
            </el-descriptions-item>
            <el-descriptions-item label="饮食需求">
              <el-tag 
                v-for="need in currentUser.preference.dietary_needs"
                :key="need"
                style="margin-right: 4px"
              >
                {{ need }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户"
      width="40%"
    >
      <el-form v-if="currentUser" :model="currentUser" label-width="100px">
        <el-form-item label="邮箱">
          <el-input v-model="currentUser.Email" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="currentUser.Phone" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="currentUser.Role">
            <el-option label="管理员" value="admin" />
            <el-option label="用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentUser.Status">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="blocked" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

// 定义与后端对应的接口
interface UserPreference {
  fav_categories: string[]
  fav_tags: string[]
  spicy_level: number
  dietary_needs: string[]
}

interface UserStats {
  total_orders: number
  total_amount: number
  avg_order_amount: number
}

interface User {
  ID: number
  Username: string
  Email: string
  Role: string
  Status: string
  LastLoginAt: string
  CreatedAt: string
  Points: number
  preference?: UserPreference
  stats?: UserStats
}

const store = useStore()
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const users = ref<User[]>([])
const searchQuery = ref('')
const detailDialogVisible = ref(false)
const currentUser = ref<User | null>(null)
const editDialogVisible = ref(false)

const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 加载用户列表
const loadUsers = async () => {
  loading.value = true
  try {
    const response = await fetch('http://localhost:8080/api/users', {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const text = await response.text() // 先获取原始文本
    console.log('Raw response:', text) // 打印原始响应
    
    try {
      const data = JSON.parse(text) // 尝试解析 JSON
      console.log('Parsed data:', data)
      users.value = data.users || []
    } catch (e) {
      console.error('JSON parse error:', e)
      throw e
    }
  } catch (error) {
    console.error('Load users error:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

// 查看用户详情
const handleViewDetails = async (user: User) => {
  try {
    const response = await fetch(`http://localhost:8080/api/users/${user.ID}`, { // 修改 API 路径
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    if (response.ok) {
      currentUser.value = data.user
      detailDialogVisible.value = true
    } else {
      ElMessage.error(data.error || '获取用户详情失败')
    }
  } catch (error) {
    ElMessage.error('获取用户详情失败')
  }
}

// 更新用户状态
const handleUpdateStatus = async (user: User, newStatus: string) => {
  try {
    const response = await fetch(`http://localhost:8080/api/users/${user.ID}/status`, { // 修改 API 路径
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${store.state.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ status: newStatus })
    })

    if (response.ok) {
      ElMessage.success('更新用户状态成功')
      loadUsers()
    } else {
      const data = await response.json()
      ElMessage.error(data.error || '更新用户状态失败')
    }
  } catch (error) {
    ElMessage.error('更新用户状态失败')
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadUsers()
}

// 处理分页
const handlePageChange = (page: number) => {
  currentPage.value = page
  loadUsers()
}

// 删除用户
const handleDelete = async (user: User) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${user.Username} 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await fetch(`http://localhost:8080/api/users/${user.ID}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })

    if (response.ok) {
      ElMessage.success('删除用户成功')
      loadUsers()
    } else {
      const data = await response.json()
      ElMessage.error(data.error || '删除用户失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除用户失败')
    }
  }
}

// 编辑用户
const handleEdit = async (user: User) => {
  currentUser.value = { ...user }
  editDialogVisible.value = true
}

// 保存用户信息
const handleSave = async () => {
  if (!currentUser.value) return
  
  try {
    const response = await fetch(`http://localhost:8080/api/users/${currentUser.value.ID}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${store.state.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: currentUser.value.Email,
        phone: currentUser.value.Phone,
        role: currentUser.value.Role,
        status: currentUser.value.Status
      })
    })

    if (response.ok) {
      ElMessage.success('更新用户信息成功')
      editDialogVisible.value = false
      loadUsers()
    } else {
      const data = await response.json()
      ElMessage.error(data.error || '更新用户信息失败')
    }
  } catch (error) {
    ElMessage.error('更新用户信息失败')
  }
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.user-details {
  padding: 20px;
}

.user-details h3 {
  margin-bottom: 16px;
  font-weight: 500;
}
</style> 